﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
//using Microsoft.Reporting.WinForms;

namespace SSRSViewer.Core
{
	public class RdlParser
	{
		IDbConnection Connection { get; set; }
		XmlDocument ReportDocument { get; set; }
		public IList<RdlDataProvider> DataProviders { get; private set; }
		public IList<RdlReportParameter> ReportParameters { get; private set; }

		public RdlParser(Stream stream, IDbConnection cn)
		{
			DataProviders = new List<RdlDataProvider>();
			ReportParameters = new List<RdlReportParameter>();

			if (stream == null)
				throw new ArgumentNullException("stream");
			if (cn == null)
				throw new ArgumentNullException("cn");

			Connection = cn;

			try
			{
				if (stream.CanSeek)
					stream.Seek(0, 0);
				ReportDocument = new XmlDocument();
				ReportDocument.Load(stream);
			}
			catch (XmlException ex)
			{
				throw ex;
			}

			if (ReportDocument.DocumentElement.Name != "Report")
				throw new ArgumentOutOfRangeException("Stream does not contain a valid Rdl Document.");

			XmlNodeList datasets = ReportDocument.DocumentElement.GetElementsByTagName("DataSets")[0].ChildNodes;

			foreach (XmlNode dsNode in datasets)
				DataProviders.Add(new RdlDataProvider(dsNode));

			// Parse the report parameters.
			XmlNodeList XmlReportParameters = ReportDocument.DocumentElement.GetElementsByTagName("ReportParameters");
			if (XmlReportParameters.Count > 0)
			{
				XmlNodeList rptParams = XmlReportParameters[0].ChildNodes;
				foreach (XmlNode rptParam in rptParams)
					ReportParameters.Add(new RdlReportParameter(Connection, rptParam, DataProviders));
			}
		}
	}
}